<template>
    <el-row>
        <el-col :span="24">
            <div class="grid-content ep-bg-purple-dark" />
            <el-card>
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item>
                        <el-row>
                            <el-col :span="7">
                                <el-button type="success" style="width: 50px;" @click="showAddDialog">添加</el-button>
                            </el-col>
<!--                            <el-col :span="7">-->
<!--                                <el-button type="success" style="width: 100%; margin-right: 10px;" @click="exportExcel">下载</el-button>-->
<!--                            </el-col>-->
<!--                            <el-col :span="7">-->
<!--                                <el-form-item style="padding-bottom: 10px; width: 100%">-->
<!--                                    <el-upload class="upload-demo" action="http://localhost:8080/admin/owner/importExcel" name="file"-->
<!--                                               :before-upload="beforeExcelUpload" :on-exceed="handleExcelSuccess" :limit="1"-->
<!--                                               accept=".xls,.xlsx" :headers="headers">-->
<!--                                        <el-button type="primary" style="width: 100%">导入数据</el-button>-->
<!--                                    </el-upload>-->
<!--                                </el-form-item>-->
<!--                            </el-col>-->
                        </el-row>
                    </el-form-item>
                    <el-form-item style="float: right;">
                        <el-input v-model="searchCondition.oname" placeholder="请输入设备名称查询" @input="onSearch" />
                    </el-form-item>
                    <el-form-item style="float: right;">
                        <el-input v-model="searchCondition.ophone" placeholder="请输入存放地址查询" @input="onSearch" />
                    </el-form-item>

                </el-form>
                <el-table :data="pageInfo.list" border style="width: 100%">
                    <el-table-column prop="oid" label="ID" width="50px" />
                    <el-table-column prop="oname" label="设备名称" />
                    <el-table-column prop="ophone" label="设备编号" />
                    <el-table-column prop="address" label="存放地址" />
                    <el-table-column label="设备状态" width="140px">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.ogender)" size="large">
                                {{ getStatusText(scope.row.ogender) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="selectByoid(scope.row.oid)">修改</el-button>
                            <el-popconfirm title="你确定要删除嘛" confirm-button-text="确认" cancel-button-text="取消"
                                           @confirm="deleteByOid(scope.row.oid)">
                                <template #reference>
                                    <el-button size="small" type="danger">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row class="row-bg" justify="center" style="margin-top: 20px;">
                    <el-pagination background layout="prev, pager, next" :total="pageInfo.total"
                                   :page-size="pageInfo.pageSize" @change="selectByPage" />
                </el-row>
            </el-card>
        </el-col>
    </el-row>
    <!--添加业主的对话框开始-->
    <el-dialog v-model="addDialogshow" title=" 添加设备" width="500">
        <el-form>
            <el-form-item label="设备名称" label-width="20%">
                <el-input v-model="ownerAdd.oname" v-autocomplete="off" />
            </el-form-item>
            <el-form-item label="设备状态" label-width="20%">
                <el-radio-group v-model="ownerAdd.ogender">
                    <el-radio value="1" size="large">正常运行</el-radio>
                    <el-radio value="2" size="large">损坏维修中</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="设备编号" label-width="20%">
                <el-input v-model="ownerAdd.ophone" v-autocomplete="off" />
            </el-form-item>
            <el-form-item label="存放地址" label-width="20%">
                <el-input v-model="ownerAdd.address" v-autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addDialogshow = false">取消</el-button>
                <el-button type="primary" @click="insert">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!--添加业主的对话框结束-->
    <!--修改业主的对话框开始-->
    <el-dialog v-model="updateDialogShow" title=" 修改设备" width="500">
        <el-form>
            <el-form-item label="设备名称" label-width="20%">
                <el-input v-model="ownerUpdate.oname" v-autocomplete="off" />
            </el-form-item>
            <el-form-item label="设备状态" label-width="20%">
                <el-radio-group v-model="ownerUpdate.ogender">
                    <el-radio value="1" size="large">正常运行</el-radio>
                    <el-radio value="2" size="large">损坏维修中</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="设备编号" label-width="20%">
                <el-input v-model="ownerUpdate.ophone" v-autocomplete="off" />
            </el-form-item>
            <el-form-item label="存放地址" label-width="20%">
                <el-input v-model="ownerUpdate.address" v-autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updateDialogShow = false">取消</el-button>
                <el-button type="primary" @click="update">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!--修改业主的对话框结束-->
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import ownerApi from '@/api/ownerApi';
import { useTokenStore } from '@/stores/token';

const tokenStore = useTokenStore();

// 上传文件 headers
const headers = () => ({
    token: tokenStore.tokenStr
});

// 状态配置（数字 => 文字 + 颜色类型）
const statusConfig = {
    '1': { text: '正常运行', type: 'success' }, // 绿色
    '2': { text: '损坏维修中', type: 'danger' }  // 红色
};

// 添加对话框状态
const addDialogshow = ref(false);
const updateDialogShow = ref(false);
const pageInfo = ref({ total: 0, pageSize: 0 });
const searchCondition = reactive({ oname: '', ophone: '' });

// 被添加/修改的业主信息
const ownerAdd = ref({
    oname: '',
    ogender: '',
    ophone: '',
    address: ''
});

const ownerUpdate = ref({
    oid: '',
    oname: '',
    ogender: '',
    ophone: '',
    address: ''
});

// 获取状态文字
function getStatusText(ogender) {
    return statusConfig[ogender]?.text || '未知状态';
}

// 获取状态颜色类型
function getStatusType(ogender) {
    return statusConfig[ogender]?.type || 'warning';
}

// 显示添加对话框
function showAddDialog() {
    ownerAdd.value = {
        oname: '',
        ogender: '',
        ophone: '',
        address: ''
    };
    addDialogshow.value = true;
}

// 分页查询
function selectByPage(pageNum) {
    ownerApi.selectByPage(pageNum, searchCondition)
        .then(resp => {
            pageInfo.value = resp.data;
        })
        .catch(error => {
            ElMessage.error('获取数据失败：' + error.message);
        });
}

// 搜索方法
function onSearch() {
    selectByPage(1);
}

// 导出 Excel
function exportExcel() {
    ownerApi.exportExcel()
        .then(resp => {
            const blob = new Blob([resp], { type: 'application/xlsx' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = '设备信息表.xlsx';
            link.click();
            URL.revokeObjectURL(url);
            ElMessage.success('导出成功');
        })
        .catch(error => {
            ElMessage.error('导出失败：' + error.message);
        });
}

// 上传 Excel 前验证
function beforeExcelUpload(rawFile) {
    const allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'];
    if (!allowedTypes.includes(rawFile.type)) {
        ElMessage.error('仅支持 .xlsx 或 .xls 格式');
        return false;
    }
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过 2MB');
        return false;
    }
    ElMessage.success('文件上传成功');
    return true;
}

// 导入成功处理
function handleExcelSuccess() {
    // 可选：导入成功后刷新数据
    selectByPage(1);
}

// 修改业主信息
function update() {
    const loading = ElLoading.service();
    ownerApi.update(ownerUpdate.value)
        .then(resp => {
            loading.close();
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
                updateDialogShow.value = false;
                selectByPage(pageInfo.value.pageNum);
            } else {
                ElMessage.error(resp.msg);
            }
        })
        .catch(error => {
            loading.close();
            ElMessage.error('修改失败：' + error.message);
        });
}

// 根据 ID 查询业主信息
function selectByoid(oid) {
    ownerApi.selectById(oid)
        .then(resp => {
            ownerUpdate.value = { ...resp.data };
            updateDialogShow.value = true;
        })
        .catch(error => {
            ElMessage.error('查询失败：' + error.message);
        });
}

// 添加业主信息
function insert() {
    const loading = ElLoading.service();
    ownerApi.insert(ownerAdd.value)
        .then(resp => {
            loading.close();
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
                addDialogshow.value = false;
                ownerAdd.value = { oname: '', ogender: '', ophone: '', address: '' };
                selectByPage(pageInfo.value.pageNum);
            } else {
                ElMessage.error(resp.msg);
            }
        })
        .catch(error => {
            loading.close();
            ElMessage.error('添加失败：' + error.message);
        });
}

// 删除业主信息
function deleteByOid(oid) {
    const loading = ElLoading.service();
    ownerApi.delete(oid)
        .then(resp => {
            loading.close();
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
                selectByPage(pageInfo.value.pageNum);
            } else {
                ElMessage.error(resp.msg);
            }
        })
        .catch(error => {
            loading.close();
            ElMessage.error('删除失败：' + error.message);
        });
}

// 初始化加载数据
selectByPage(1);
</script>

<style scoped>
/* 可选：调整标签样式 */
.el-tag {
    font-size: 14px;
    padding: 4px 12px;
}
</style>